package com.infore.statisticsAndAlarm.controller;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.infore.statisticsAndAlarm.enums.ResultStatus;
import com.infore.statisticsAndAlarm.util.MD5Util;
import com.infore.statisticsAndAlarm.util.ResultEntity;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;



@Controller
public class TestController {
	
	@SuppressWarnings("unused")
	private static BasicCookieStore cookieStore;
	
	@Autowired
    private RestTemplate restTemplate;
	
	@SuppressWarnings("unused")
	private static final Logger logger = LoggerFactory.getLogger(TestController.class);
	
	@ApiOperation(value = "测试接口")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "msg", value = "测试参数", paramType = "query", required = true, dataType = "String"),
	})
	@RequestMapping(value = "/test/msg", method = RequestMethod.GET )
	@ResponseBody
	public ResultEntity test() {
		//headers
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Authorization", "datashare=D186A13D5AC53698DF1064D982350C2E");
        requestHeaders.add("Content-Type", "application/json");
        //body
        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("Authorization", "datashare=D186A13D5AC53698DF1064D982350C2E");
        requestBody.add("Content-Type", "application/json");
        HttpEntity<MultiValueMap<String,String>> requestEntity = new HttpEntity<>(requestBody, requestHeaders);
        long start = System.currentTimeMillis();
        String url = "http://106.37.208.243:8067/RBACService/RBAC/GetGJZMNList";
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        long end = System.currentTimeMillis();
        long cost = end - start;
        System.out.println("耗时："+cost);
        String body = responseEntity.getBody();
        System.out.println("响应体："+ body);
        
        ResultEntity resultEntity = new ResultEntity(ResultStatus.SUCCESS,"收到的消息为：",body);
		return resultEntity;
	}
	
	
	@ApiOperation(value = "模拟登录")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "msg", value = "测试参数", paramType = "query", required = true, dataType = "String"),
	})
	@RequestMapping(value = "/login", method = RequestMethod.GET )
	@ResponseBody
	public ResultEntity login(HttpServletRequest request) throws Exception {
		//headers
//        HttpHeaders requestHeaders = new HttpHeaders();
//        requestHeaders.add("Connection", "keep-alive");
//        requestHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) "
//        		+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
//        requestHeaders.add("Content-Type", "application/x-www-form-urlencoded");
//        
//        HttpEntity<MultiValueMap<String,String>> requestEntity = new HttpEntity<>(null, requestHeaders);
//        String url = "http://106.37.208.243:8068/LoginGJZ.aspx";
//        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
//        String body = responseEntity.getBody();
//        
//        
//        requestHeaders = new HttpHeaders();
//        requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        Set<String> list = responseEntity.getHeaders().keySet();
//        requestHeaders.setCacheControl(responseEntity.getHeaders().getCacheControl());
//        
//        //body
//        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
//        requestBody.add("txtUserNme", "yxxiekang");
//        requestBody.add("password", "yx123456");
//        
//        requestEntity = new HttpEntity<>(requestBody, requestHeaders);
//        url = "http://106.37.208.243:8068/LoginGJZ.aspx";
//        responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
//        body = responseEntity.getBody();
        
		
		
		// 全局请求设置
	    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
	    // 创建cookie store的本地实例
	    CookieStore cookieStore = new BasicCookieStore();
	    // 创建HttpClient上下文
	    HttpClientContext context = HttpClientContext.create();
	    context.setCookieStore(cookieStore);
	 
	    // 创建一个HttpClient
	    CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
	        .setDefaultCookieStore(cookieStore).build();
        
	    CloseableHttpResponse res = null;
	    
	 // 创建本地的HTTP内容
	    try {
	      try {
	        // 创建一个get请求用来获取必要的Cookie，如_xsrf信息
	        HttpGet get = new HttpGet("http://106.37.208.243:8068/GJZ/Business/Publish/Main.aspx");
	 
	        res = httpClient.execute(get, context);
	        String content = EntityUtils.toString(res.getEntity());
	        content = content.substring(content.indexOf("id=\"__VIEWSTATE\" value=")+24, content.indexOf("<input type=\"hidden\" name=\"__EVENTVALIDATION\"")).trim();
	        content = content.substring(0, content.indexOf("\" />"));
	        System.out.println("66666666666666"+content);
	        
	        // 获取常用Cookie,包括_xsrf信息
	        System.out.println("访问首页后的获取的常规Cookie:===============");
	        for (org.apache.http.cookie.Cookie c : cookieStore.getCookies()) {
	          System.out.println(c.getName() + ": " + c.getValue());
	        }
	        res.close();
	        
	        
	        
	        String result = MD5Util.getMD5String("yx123456");
	        // 构造post数据
	        List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();
	        valuePairs.add(new BasicNameValuePair("__VIEWSTATE", "%2FwEPDwUKMTEzMTg0NTQ3M2QYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFDWNoa1JlbWVtYmVyTWUcnY0GvBxmqqRFOn%2BhQPmpgXmH3EglYGkibCuehv%2FRBw%3D%3D&__EVENTVALIDATION=%2FwEdAAaAytBHY4QhGgFnU5iGwrbcdJFG%2FQ7eo6Ve1Hska16v2HTpoIpf76wCWOsMOH7Urv4XdwSgMknwRrTITBdcf2yNW%2B%2F3Q%2BiOJ%2Fl%2Fi%2BaGJIMWF%2BYeW%2FbI7mQN6iEbHCTuNBaC2I5t30B8PuVtEkNeuJw6JMk5JKHeMOEML2wRausYAQ%3D%3D&butOK=%E7%99%BB%C2%A0%C2%A0%E5%BD%95&"));
//	        valuePairs.add(new BasicNameValuePair("__EVENTVALIDATION", "/wEdAAaAytBHY4QhGgFnU5iGwrbcdJFG/Q7eo6Ve1Hska16v2HTpoIpf76wCWOsMOH7Urv4XdwSgMknwRrTITBdcf2yNW+/3Q+iOJ/l/i+aGJIMWF+YeW/bI7mQN6iEbHCTuNBaC2I5t30B8PuVtEkNeuJw6JMk5JKHeMOEML2wRausYAQ=="));
	        valuePairs.add(new BasicNameValuePair("txtUserNme", "yxxiekang"));
	        valuePairs.add(new BasicNameValuePair("hidBaoBiao", result));
	        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);
	        entity.setContentType("application/x-www-form-urlencoded");
	 
	        // 创建一个post请求
	        HttpPost post = new HttpPost("http://106.37.208.243:8068/LoginGJZ.aspx");
	        // 注入post数据
	        post.setEntity(entity);
	        res = httpClient.execute(post, context);
	 
	        // 打印响应信息，查看是否登陆是否成功
	        System.out.println("打印响应信息===========");
	        content = EntityUtils.toString(res.getEntity());
	        System.out.println(content);
//	        HttpClientUtils.printResponse(res);
	        res.close();
	 
	        System.out.println("登陆成功后,新的Cookie:===============");
	        for (org.apache.http.cookie.Cookie c : context.getCookieStore().getCookies()) {
	          System.out.println(c.getName() + ": " + c.getValue());
	        }
	 
	        // 构造一个新的get请求，用来测试登录是否成功
	        String dataUrl = "http://106.37.208.243:8068/GJZ/Business/SJSH/DataAuxiliary/ParasHisData_List.aspx?"
            		+ "action=query&vMN=A360100_0008&vDateTime=2019-03-27&vEDateTime=2019-04-10&vLHCode=w01010&iCheck=false";
	        HttpGet newGet = new HttpGet(dataUrl);
	        res = httpClient.execute(newGet, context);
	        content = EntityUtils.toString(res.getEntity());
	        System.out.println("登陆成功后访问的页面===============");
	        System.out.println(content);
	        res.close();
	 
	      } finally {
	        httpClient.close();
	      }
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
        
        
        
        
        
        
        
        
//        CloseableHttpClient httpClient =  HttpClients.custom()
//                .setDefaultCookieStore(cookieStore)
//                .build();
//        HttpPost post=new HttpPost("http://106.37.208.243:8068/LoginGJZ.aspx");
//        
//        String result = MD5Util.getMD5String("yx123456");
//        Map<String, String> keyMap = new HashMap<>();
//        keyMap.put("txtUserNme", "yxxiekang");
//        keyMap.put("hidBaoBiao", result);
//        keyMap.put("__VIEWSTATE", "%2FwEPDwUKMTEzMTg0NTQ3M2QYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFDWNoa1JlbWVtYmVyTWUcnY0GvBxmqqRFOn%2BhQPmpgXmH3EglYGkibCuehv%2FRBw%3D%3D&__EVENTVALIDATION=%2FwEdAAaAytBHY4QhGgFnU5iGwrbcdJFG%2FQ7eo6Ve1Hska16v2HTpoIpf76wCWOsMOH7Urv4XdwSgMknwRrTITBdcf2yNW%2B%2F3Q%2BiOJ%2Fl%2Fi%2BaGJIMWF%2BYeW%2FbI7mQN6iEbHCTuNBaC2I5t30B8PuVtEkNeuJw6JMk5JKHeMOEML2wRausYAQ%3D%3D&butOK=%E7%99%BB%C2%A0%C2%A0%E5%BD%95&");
//        
//        for (Map.Entry<String, String> entry : keyMap.entrySet()) {
//        	post.addHeader(entry.getKey(), entry.getValue());
//        }
//        HttpClientContext context = HttpClientContext.create();
//        try {
//            CloseableHttpResponse response = httpClient.execute(post, context);
//            try{
//                System.out.println(">>>>>>headers:");
//                Arrays.stream(response.getAllHeaders()).forEach(System.out::println);
//                System.out.println(">>>>>>cookies:");
//                context.getCookieStore().getCookies().forEach(System.out::println);
//                
//                
////                httpClient = HttpClients.createDefault();
//                String dataUrl = "http://106.37.208.243:8068/GJZ/Business/SJSH/DataAuxiliary/ParasHisData_List.aspx?"
//                		+ "action=query&vMN=A360100_0008&vDateTime=2019-03-27&vEDateTime=2019-04-10&vLHCode=w01010&iCheck=false";
//                HttpGet get=new HttpGet(dataUrl);
//                HttpClientContext context1 = HttpClientContext.create();
//                context1.setCookieStore(context.getCookieStore());
////                get.addHeader("",);
//                response = httpClient.execute(get, context1);
//                org.apache.http.HttpEntity entityRes = response.getEntity();
//                String mString = EntityUtils.toString(entityRes, "UTF-8");
//                System.out.println(mString);
//                
//            }
//            finally {
//                response.close();
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }finally {
//            try {
//                httpClient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        ResultEntity resultEntity = new ResultEntity(ResultStatus.SUCCESS,"收到的消息为：","");
		return resultEntity;
	}
	
	
	
	@SuppressWarnings("unused")
	private static String readJSFile(HttpServletRequest request) throws Exception { 
        StringBuffer script = new StringBuffer(); 
        String realPath=request.getServletContext().getRealPath("/")+"md6.js";
        File file = new File(realPath); 
        FileReader filereader = new FileReader(file); 
        BufferedReader bufferreader = new BufferedReader(filereader); 
        String tempString = null; 
        while ((tempString = bufferreader.readLine()) != null) { 
            script.append(tempString).append("\n"); 
        } 
        bufferreader.close(); 
        filereader.close(); 
        return script.toString(); 
    }

}
